import { Subject } from "rxjs";

export class SelectItems {
    public selectedItems: string[];
    private idName: string;
    public selectedItemsSubject: Subject<Array<string>>
    constructor(idName: string) {
        this.selectedItemsSubject = new Subject<Array<string>>();
        this.selectedItems = [];
        this.idName = idName
    }
    public isSeleted(val: string, arr?: Array<string>): string | boolean {
        arr = arr ? arr : this.selectedItems
        let isExist = arr.findIndex(each => each === val);
        if (isExist > -1) {
            return isExist + ''
        } else {
            return false
        }
    }
    public selectThis(val: string, arr?: Array<string>): void {
        arr = arr ? arr : this.selectedItems
        let key = this.isSeleted(val, arr)
        if (key) {
            arr.splice(+key, 1)
        } else {
            arr.push(val)
        }
        this.selectedItemsSubject.next(this.selectedItems)
    }
    public sendSelectedItems(val: string): void {
        this.selectThis(val, this.selectedItems);
        this.selectedItemsSubject.next(this.selectedItems)
    }
    public selectAll(tabVal: Array<any>) {
        if (this.selectedItems.length < tabVal.length) {
            this.selectedItems = [];
            tabVal.map(each => {
                this.selectedItems.push(each[this.idName])
            })
        } else {
            this.selectedItems = []
        }
        this.selectedItemsSubject.next(this.selectedItems)
    }
    public clearSelectedItems() {
        this.selectedItems = [];
        this.selectedItemsSubject.next(this.selectedItems)
    }
    public isSelectAll(length: string | number) {
        return this.selectedItems.length == length && length != 0
    }
}